package com.example.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.controller.utils.R;
import com.example.domain.Book;
import com.example.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping()
    public R getAll() throws Exception {
       return  new R(true,bookService.getAll());
    }
    @PostMapping()
    public R save(@RequestBody Book book) throws Exception {
        boolean flag =    bookService.save(book) ;
        if(book.getName().equals("123"))  throw  new Exception();

        return new R(flag,flag ?"添加成功":"添加失败");
    }
    @PutMapping()
    public R update(@RequestBody Book book) throws Exception {
        return new R(bookService.update(book));

    }
    @DeleteMapping("{id}")
    public R delete(@PathVariable int id){
        return new R(bookService.delete(id));

    }

    @GetMapping("{id}")
    public R getById(@PathVariable int id ){
        return new R(bookService.getById(id)!=null,bookService.getById(id));
    }
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize,Book book){
//        System.out.println("参数==>"+book);

        IPage<Book> page = bookService.getPage(currentPage, pageSize,book);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if( currentPage > page.getPages()){
            page = bookService.getPage((int)page.getPages(), pageSize,book);
        }
        return new R(true, page);
    }
}
